// import { cookieGet } from '@/common/cookie'
import Cookies from "js-cookie";
import qs from 'qs'
export default {
  data () {
    /* eslint-disable */
    return {
      // 设置属性
      mixinViewModuleOptions: {
        activatedIsNeed: true,    // 此页面是否在激活（进入）时，调用查询数据列表接口？
        getDataListURL: '',       // 数据列表接口，API地址
        getDataListIsPage: false, // 数据列表接口，是否需要分页？
        deleteURL: '',            // 删除接口，API地址
        deleteIsBatch: false,     // 删除接口，是否需要批量？
        deleteIsBatchKey: 'id',   // 删除接口，批量状态下由那个key进行标记操作？比如：pid，uid...
        exportURL: '',             // 导出接口，API地址
        enableURL: ''             // 启用/禁用接口，API地址
      },
      // 默认属性
      dataForm: {},
      queryItems: [],             // 查询条件 EQ(1, "等于"), LIKE(2, "模糊查询:'%王%'"), LIKELEFT(3, "左模糊查询:'%王'"), LIKERIGHT(4, "右模糊查询:'王%'"), GE(5, "大于等于"),LE(6, "小于等于");
      dataList: [],               // 数据列表
      order: '',                  // 排序，ASC／DESC
      orderField: '',             // 排序，字段
      page: 1,                    // 当前页码
      limit: 10,                  // 每页数
      total: 0,                   // 总条数
      dataListLoading: false,     // 数据列表，loading状态
      dataListSelections: [],     // 数据列表，多选项
      addOrUpdateVisible: false,  // 新增／更新，弹窗visible状态
      isShowTemplateEditVisible: false  // 合同模板编辑显示
    }
    /* eslint-enable */
  },
  activated () {
    if (this.mixinViewModuleOptions.activatedIsNeed) {
      this.getDataList()
    }
  },
  created () {
    if (this.mixinViewModuleOptions.activatedIsNeed) {
      this.getDataList()
    }
  },
  methods: {
    // 获取数据列表
    getDataList () {
      this.dataListLoading = true
      this.$axios.get(
        this.mixinViewModuleOptions.getDataListURL,
        {
          params: {
            order: this.order,
            orderField: this.orderField,
            current: this.mixinViewModuleOptions.getDataListIsPage ? this.page : null,
            size: this.mixinViewModuleOptions.getDataListIsPage ? this.limit : null,
            queryItems: this.createQueryParams(this.queryItems)
          }
        }
      ).then(res => {
        this.dataListLoading = false
        this.dataList = this.mixinViewModuleOptions.getDataListIsPage ? res.data.records : res.data.records
        this.total = this.mixinViewModuleOptions.getDataListIsPage ? res.data.total : 0
      }).catch(() => {
        this.dataList = []
        this.total = 0
        this.dataListLoading = false
      })
    },
    queryDataList () {
      this.dataListLoading = true
      this.$axios.get(
          this.mixinViewModuleOptions.getDataListURL,
          {
            params: {
              order: this.order,
              orderField: this.orderField,
              current: this.mixinViewModuleOptions.getDataListIsPage ? this.page : null,
              size: this.mixinViewModuleOptions.getDataListIsPage ? this.limit : null,
              ...this.queryItems
            }
          }
      ).then(res => {
        this.dataListLoading = false
        this.dataList = this.mixinViewModuleOptions.getDataListIsPage ? res.data.records : res.data.records
        this.total = this.mixinViewModuleOptions.getDataListIsPage ? res.data.total : 0
      }).catch(() => {
        this.dataList = []
        this.total = 0
        this.dataListLoading = false
      })
    },
    //查询条件构造器
    createQueryParams(queryItems){
      let queryParams = ''
      if(queryItems.length > 0){
        for (let i = 0; i < queryItems.length; i++) {
          let queryItem = queryItems[i]
          queryParams = queryParams + queryItem.field + ',' + queryItem.as + ',' + queryItem.value + ';'
        }
      }
      return queryParams
    },
    // 多选
    dataListSelectionChangeHandle (val) {
      this.dataListSelections = val
    },
    // 排序
    dataListSortChangeHandle (data) {
      if (!data.order || !data.prop) {
        this.order = ''
        this.orderField = ''
        return false
      }
      this.order = data.order.replace(/ending$/, '').toUpperCase()
      // 将驼峰标识转成_;如:createTime ---> create_time
      // this.orderField = data.prop.replace(/([A-Z])/g, '_$1').toLowerCase()
      this.orderField = data.prop
      this.getDataList()
    },
    // 分页, 每页条数
    pageSizeChangeHandle (val) {
      this.page = 1
      this.limit = val
      this.getDataList()
    },
    // 分页, 当前页
    pageCurrentChangeHandle (val) {
      this.page = val
      this.getDataList()
    },
    // 分页, 每页条数
    pageSizeQueryChangeHandle (val) {
      this.page = 1
      this.limit = val
      this.queryDataList()
    },
    // 分页, 当前页
    pageCurrentQueryChangeHandle (val) {
      this.page = val
      this.queryDataList()
    },
    // 新增 / 修改
    addOrUpdateHandle (id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.dataForm.id = id
        this.$refs.addOrUpdate.init()
      })
    },
    // 删除
    deleteHandle (id) {
      if (this.mixinViewModuleOptions.deleteIsBatch && !id && this.dataListSelections.length <= 0) {
        return this.$message({
          message: '批量删除',
          type: 'warning',
          duration: 500
        })
      }
      this.$confirm('确定进行删除操作?' , '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete(
          `${this.mixinViewModuleOptions.deleteURL}${this.mixinViewModuleOptions.deleteIsBatch ? '' : '/' + id}`,
          this.mixinViewModuleOptions.deleteIsBatch ? {
            'data': id ? [id] : this.dataListSelections.map(item => item[this.mixinViewModuleOptions.deleteIsBatchKey])
          } : {}
        ).then(res => {
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.getDataList()
            }
          })
        }).catch(() => {})
      }).catch(() => {})
    },
    // 导出
    exportHandle () {
      var params = qs.stringify({
        'token': Cookies.get('token'),
        ...this.dataForm
      })
      window.location.href = `${window.SITE_CONFIG['apiURL']}${this.mixinViewModuleOptions.exportURL}?${params}`
    },

    //禁用/启用
    enableHandle(row){
      let dataItem = Object.assign({}, row) //拷贝数据对象
      dataItem.status = dataItem.status === 1 ? 0 : 1
      let params =  {
        id:dataItem.id,
        type: dataItem.type,
        status:dataItem.status
      };
      this.$http.post(this.mixinViewModuleOptions.enableURL, params).then(res => {
        this.$message({
          message: '操作成功',
          type: 'success',
          duration: 500,
          onClose: () => {
            this.visible = false
            this.getDataList()
          }
        })
      }).catch(() => {})
    },

    //显示合同模板编辑
    showTemplateEdit (id) {
      this.isShowTemplateEditVisible = true
      this.$nextTick(() => {
        this.$refs.templateEdit.dataForm.id = id
        this.$refs.templateEdit.init()
      })
    }

  }
}
